package com.cos.hospital.ui.record.edit;

import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.text.Selection;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

import com.cos.hospital.R;
import com.cos.hospital.code.Code;
import com.cos.hospital.model.UHttp;
import com.cos.hospital.model.bean.ErrorBean;
import com.cos.hospital.model.bean.ImageBean;
import com.cos.hospital.model.bean.RecordWebBean;
import com.cos.hospital.model.bean.ResultBean;
import com.cos.hospital.model.bean.ResultListBean;
import com.cos.hospital.model.bean.UploadBean;
import com.cos.hospital.model.connector.HttpMsgListener;
import com.cos.hospital.tool.SPUtil;
import com.cos.hospital.tool.UDialog;
import com.cos.hospital.tool.UKeyboard;
import com.cos.hospital.tool.UPoPImages;
import com.cos.hospital.tool.UToast;
import com.cos.hospital.tool.UTxt;
import com.cos.hospital.tool.glide.UGlide;
import com.cos.hospital.ui.other.YinShiTuPianActivity;
import com.cos.hospital.ui.record.RecordBaseActivity;
import com.cos.hospital.ui.record.RecordCode;
import com.cos.hospital.widget.ProgressDialog;
import com.google.gson.JsonObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnLongClick;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * @Description: 编辑: 舌脉象、治疗处方
 * @Author: Kosmos
 * @Date: 2018年09月26日 23:52
 * @Email: KosmoSakura@foxmail.com
 */
public class EditorTongueActivity extends RecordBaseActivity implements View.OnTouchListener {
    @BindView(R.id.rec_edt_main_lay)
    View rootLay;
    @BindView(R.id.rec_tongue_img_1)
    ImageView img1;
    @BindView(R.id.rec_tongue_img_2)
    ImageView img2;
    @BindView(R.id.rec_tongue_img_3)
    ImageView img3;
    private String[] urls;
    private int point;//指针
    private ImageView[] imgs;
    private UPoPImages pImages;

    @Override
    protected int layout() {
        return R.layout.activity_editor_tongue;
    }

    @Override
    protected void initData() {
        setTitleLeftIcon();
        setTitleRightTxt(getString(R.string.save));
        switch (fldEleID) {
            case RecordCode.Type.TonguePulse://舌脉象:
                setTitleCenterTxt(getString(R.string.tongue_edit));
                edtMain.setHint(R.string.please_enter_tongue);
                break;
            case RecordCode.Type.Prescription://治疗处方:
                setTitleCenterTxt(getString(R.string.prescription_edit));
                edtMain.setHint(R.string.please_enter_prescription);
                break;
        }
        changeBtnState(tVoice, StateOFF);
        changeBtnState(tTemplate, StateOFF);
        changeBtnState(tFormula, StateNone);
        changeBtnState(tTakephoto, StateOFF);
        initTemplateAdapter();
        urls = new String[3];
        imgs = new ImageView[]{img1, img2, img3};
        if (!UTxt.isEmpty(imageBeanList)) {
            int size = imageBeanList.size();
            size = size > 3 ? 3 : size;
            for (int i = 0; i < size; i++) {
                ImageBean imageBean = imageBeanList.get(i);
                urls[i] = imageBean.getFldImgPath();
                UGlide.loadRound(this, urls[i], imgs[i]);
            }
        }
        point = -1;
        rootLay.setOnTouchListener(this);
        edtMain.setOnTouchListener(this);
    }

    @Override
    protected void logic() {
        Selection.setSelection(edtMain.getText(), edtMain.length());
    }

    @Override
    protected void onTemplateSelect(String content) {
//        edtMain.append(content);
//        Selection.setSelection(edtMain.getText(), edtMain.length());

        int index = edtMain.getSelectionStart();
        Editable edit = edtMain.getEditableText();
        if (index < 0 || index >= edit.length()) {
            edtMain.append(content);
        } else {
            edit.insert(index, content);
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        UKeyboard.with(this).showForce(edtMain);
        if (pImages != null && pImages.isShow()) {
            hideAllFun();
            UKeyboard.with(this).hideForce(edtMain);
        } else {
            hideAllFun();
            UKeyboard.with(this).showForce(edtMain); //打开键盘
        }
        return false;
    }

    /**
     * @param state 状态
     * @apiNote :
     * int FunVoice = 1;//语音
     * int FunTemplate = 1;//模板
     * int FunTakephoto = 1;//拍照
     */
    @Override
    protected void onFunctionBtnClick(int state) {
        switch (state) {
            case FunTemplate:
                if (firstTimeToGetTemplateList) {
                    spv.callFreshDelay(500);
                    firstTimeToGetTemplateList = false;
                }
                break;
            case FunTakephoto://拍照:
                UKeyboard.with(this).hideForce(edtMain);
                if (UTxt.isEmpty(urls[0])) {
                    point = 0;
                } else if (UTxt.isEmpty(urls[1])) {
                    point = 1;
                } else if (UTxt.isEmpty(urls[2])) {
                    point = 2;
                } else {
                    showNotice("照片已满，若要拍摄，请先删除现有照片");
                    return;
                }
                openCamrea();
                break;
        }
    }

    @Override
    protected void onSpeakBack(String result) {
        int index = edtMain.getSelectionStart();
        Editable edit = edtMain.getEditableText();
        if (index < 0 || index >= edit.length()) {
            edtMain.append(result);
        } else {
            edit.insert(index, result);
        }
    }

    @OnClick({R.id.title_next_txt, R.id.rec_tongue_img_1, R.id.rec_tongue_img_2, R.id.rec_tongue_img_3})
    public void onClicked(View view) {
        switch (view.getId()) {
            case R.id.title_next_txt://保存
                UKeyboard keyboard = UKeyboard.with(this);
                if (keyboard.isKeyboardShow()) {
                    keyboard.hideForce(edtMain);
                }
                save();
                break;
            case R.id.rec_tongue_img_1:
                imageClick(0);
                break;
            case R.id.rec_tongue_img_2:
                imageClick(1);
                break;
            case R.id.rec_tongue_img_3:
                imageClick(2);
                break;
        }
    }

    private void save() {
        boolean empty = true;
        for (String url : urls) {
            if (!UTxt.isEmpty(url)) {
                empty = false;
                break;
            }
        }
        if (empty && UTxt.isEmpty(edtMain)) {
            showNotice("保存内容不能为空");
            return;
        }
        ProgressDialog.getInstance().startProgressDialog(this);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("fldMedicalHistoryId", fldMedicalHistoryId);
        jsonObject.addProperty("fldEleID", fldEleID);
        jsonObject.addProperty("fldElementValue", UTxt.isNull(edtMain));
        jsonObject.addProperty("fldEditId", SPUtil.getUserId());
        UHttp.start(getServes().saveMedicalElement(jsonObject), "元素保存", new HttpMsgListener<ResultBean<RecordWebBean
                .MedicalElementBean>>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                ProgressDialog.getInstance().stopProgressDialog();
                showNotice(describe);
            }

            @Override
            public void onSuccess(ResultBean<RecordWebBean.MedicalElementBean> dto) {
                if (dto.isSuccess()) {
                    RecordWebBean.MedicalElementBean medicalElementBean = dto.getResult();
                    if (medicalElementBean != null) {
                        eId = medicalElementBean.getId();
                    }
                    List<ImageBean> list = new ArrayList<>();
                    for (String url : urls) {
                        if (!UTxt.isEmpty(url)) {
                            list.add(new ImageBean(url));
                        }
                    }
                    savePicture(list);
                } else {
                    ProgressDialog.getInstance().stopProgressDialog();
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }

    private void savePicture(List<ImageBean> list) {
        Map<String, Object> map = new HashMap<>();
        map.put("fldMedicalHistoryId", fldMedicalHistoryId);
        map.put("fldParentElementId", eId);
        map.put("image", list);
        map.put("fldEditId", SPUtil.getUserId());
        UHttp.start(getServes().saveMedicalImage(map), "保存元素（图片）",
                new HttpMsgListener<ResultListBean<ImageBean>>() {
                    @Override
                    public void onSubscribe(Disposable disposable) {
                        addEvent(disposable);
                    }

                    @Override
                    public void onError(String describe) {
                        showNotice(describe);
                    }

                    @Override
                    public void onFinish() {
                        ProgressDialog.getInstance().stopProgressDialog();
                    }

                    @Override
                    public void onSuccess(ResultListBean<ImageBean> dto) {
                        if (dto.isSuccess()) {
                            List<ImageBean> imageBeanList = dto.getResult();
                            UToast.toast("保存成功");
                            Intent intent = new Intent();
                            intent.putExtra(Code.SP.ID, eId);
                            intent.putExtra(Code.SP.CONTENT, UTxt.isNull(edtMain));
                            intent.putParcelableArrayListExtra(Code.SP.IMAGEBEANLIST, (ArrayList<ImageBean>) imageBeanList);
                            setResult(Activity.RESULT_OK, intent);
                            finish();
                        } else {
                            ErrorBean errorBean = dto.getError();
                            if (errorBean != null) {
                                showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                            } else {
                                showNotice(Code.DefaultPrompt);
                            }
                        }
                    }
                });
    }

    private void imageClick(int position) {
        UKeyboard keyboard = UKeyboard.with(this);
        if (keyboard.isKeyboardShow()) {
            keyboard.hideForce(edtMain);
        }
        if (UTxt.isEmpty(urls[position])) {
            point = position;
            openAlbum();
        } else {
            //pImages = UPoPImages.with(this).show(urls[position]);
            YinShiTuPianActivity.showTuPian(context, urls, position);
        }
    }

    @OnLongClick({R.id.rec_tongue_img_1, R.id.rec_tongue_img_2, R.id.rec_tongue_img_3})
    public boolean onLongClick(View view) {
        switch (view.getId()) {
            case R.id.rec_tongue_img_1:
                deleteOne(0);
                break;
            case R.id.rec_tongue_img_2:
                deleteOne(1);
                break;
            case R.id.rec_tongue_img_3:
                deleteOne(2);
                break;
        }
        return true;
    }

    private void deleteOne(int pot) {
        if (UTxt.isEmpty(urls[pot])) {
            return;
        }
        UDialog.getInstance(context, true, true)
                .showNoticeWithTwobtn("删除当前图片？", (result, dia) -> {
                    urls[pot] = "";
                    imgs[pot].setImageResource(R.mipmap.ic_photo_placeholder);
                    dia.dismiss();
                });
    }

    @Override
    public void onBackPressed() {
        if (pImages != null && pImages.isShow()) {
            pImages.hide();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void getPhotoSuccess(File file) {
        upload(file.getPath(), point);
    }

    private void upload(String compressPath, int point) {
        ProgressDialog.getInstance().startProgressDialog(this);
        File file = new File(compressPath);
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part part = MultipartBody.Part.createFormData("data", file.getName(), requestBody);
        UHttp.start(getServes().resUpload(part), "文件上传", new HttpMsgListener<ResultBean<UploadBean>>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                showNotice(describe);
            }

            @Override
            public void onFinish() {
                ProgressDialog.getInstance().stopProgressDialog();
            }

            @Override
            public void onSuccess(ResultBean<UploadBean> dto) {
                if (dto.isSuccess()) {
                    UploadBean uploadBean = dto.getResult();
                    if (uploadBean != null) {
                        String baseUrl = uploadBean.getBaseUrl();
                        String fileRelativePath = uploadBean.getFileRelativePath();
                        urls[point] = baseUrl + fileRelativePath;
                        UGlide.loadRound(context, urls[point], imgs[point]);
                    }
                } else {
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }

}
